package com.woniuxy.user.service.impl;

import static com.aliyun.teautil.Common.toJSONString;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.woniuxy.entity.AllUser;
import com.woniuxy.user.feign.OssFeignClient;
import com.woniuxy.user.mapper.UserMapper;
import com.woniuxy.user.service.UserService;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import static com.alibaba.nacos.common.remote.client.RpcClientFactory.createClient;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private OssFeignClient ossFeignClient;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Override
    public AllUser login(String username, String password) {

        return userMapper.login(username, password);
    }
    //查询电话号码是否存在，有就发验证码
    @Override
    public AllUser getCode(String phone) {
        //查询电话号码是否存在，存在就发生验证码。
//        AllUser user = userMapper.findByPhone(AESUtils.encrypt(phone));
        AllUser user = userMapper.findByPhone(phone);
        if(user != null){
            //发送验证码
            try {
                createClient(phone);
            }catch (Exception e){
                e.printStackTrace();
            }
            return user;
        }
        return null;
    }
    //校验验证码
    @Override
    public String checkCode(String phone, String code) {
        String storedCode = redisTemplate.opsForValue().get("code:" + phone);
        return storedCode;
    }
    //通过电话号码找到用户
    @Override
    public AllUser findByPhone(String phone) {
        AllUser user = userMapper.findByPhone(phone);
        return user;
    }
    //通过username找到用户
    @Override
    public AllUser findByUsername(String username) {
        AllUser user = userMapper.findByUsername(username);
        return user;
    }
    //添加用户
    @Override
    public void addUser(AllUser allUser) {
        allUser.setCreateTime(new Date());
        allUser.setUpdateTime(new Date());
        allUser.setIsDeleted(0);
        allUser.setIsAuth(0);
        allUser.setCoin(0);
        allUser.setBalance(BigDecimal.ZERO);
        userMapper.addUser(allUser);
    }

    public void createClient(String phone) throws Exception {
        Config config = new Config()
                // 配置 AccessKey ID，请确保代码运行环境配置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                .setAccessKeyId("LTAI5tPHA3RcKvnX5JVmFRZt")
                // 配置 AccessKey Secret，请确保代码运行环境配置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .setAccessKeySecret("eKRdVN4dxFKuMQMM6PYAIqzLE9o6No");
        // System.getenv()方法表示获取系统环境变量，不要直接在getenv()中填入AccessKey信息。

        // 配置 Endpoint。中国站使用dysmsapi.aliyuncs.com
        config.endpoint = "dysmsapi.aliyuncs.com";

        // 初始化请求客户端
        Client client = new Client(config);
        String code = String.valueOf((int)((Math.random() * 9 + 1) * 100000));

        // 构造API请求对象，请替换请求参数值
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(phone)
                .setSignName("阿里云短信测试")
                .setTemplateCode("SMS_154950909")
                .setTemplateParam("{'code':"+code+"}"); // TemplateParam为序列化后的JSON字符串。
        // 获取响应对象
        SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
        // 4. 存储到Redis，有效期5分钟
        redisTemplate.opsForValue().set("code:" + phone, code, 5, TimeUnit.MINUTES);
        // 响应包含服务端响应的 body 和 headers
//        System.out.println(toJSONString(sendSmsResponse));
    }
}
